import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router, { asyncRoutes } from './router'
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    // 存在token 跳转登陆页 直接中转到主页
    if (to.path === '/login') {
      next('/')
      // next（地址）并没有执行后置守卫
      NProgress.done()
      return
    }
    // 判断是否存在用户信息
    if (!store.getters.userId) {
      await store.dispatch('user/getUserInfoAction')
      // 筛选用户权限内的路由
      // 1. 筛选出用户权限内的路由
      const userInfo = store.state.user.userInfo
      const menus = userInfo.roles.menus
      // 筛选出用户权限内的路由
      const newList = asyncRoutes.filter(item => {
        return menus.includes(item.path.slice(1))
      })
      // 动态添加路由
      // 1. 向路由表中添加路由
      router.addRoutes(newList, { path: '*', redirect: '/404', hidden: true })
      // 2. 向vuex中添加路由
      store.commit('user/setRoutes', newList)
      next(to.path)
    }
    next() // 放行
  } else {
    // 没有token 判断是否路劲是否在白名单
    if (whiteList.includes(to.path)) {
      next()
      return
    }
    next('/login') // 中转到登录页
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
